package main

import (
	"dataaysn/cmd/apiroutes"
	"dataaysn/internal/repository"
	"dataaysn/internal/service"
	"dataaysn/pkg/database"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

func main() {
	// 初始化数据库连接
	db, err := database.InitDB()
	if err != nil {
		panic("failed to connect database")
	}

	// 初始化路由
	r := gin.Default()

	// 添加CORS中间件
	r.Use(func(c *gin.Context) {
		c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
		c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
		c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")

		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(204)
			return
		}

		c.Next()
	})

	setupRoutes(r, db)
	// 启动服务
	r.Run(":8086")
}

func setupRoutes(r *gin.Engine, db *gorm.DB) {

	// 初始化仓库
	taskRepo := repository.NewGormTaskRepository(db)
	taskLogRepo := repository.NewGormTaskLogRepository(db)
	mappingRuleRepo := repository.NewGormMappingRuleRepository(db)
	sshConfigRepo := repository.NewGormSSHConfigRepository(db)
	dataSourceRepo := repository.NewGormDataSourceRepository(db)
	logDrgdipRepo := repository.NewGormLogDrgDipRepository(db)

	// 初始化服务
	taskService := service.NewTaskService(taskRepo)
	taskLogService := service.NewTaskLogService(taskLogRepo)
	mappingRuleService := service.NewMappingRuleService(mappingRuleRepo)
	sshConfigService := service.NewSSHConfigService(sshConfigRepo)
	dataSourceService := service.NewDataSourceService(dataSourceRepo)
	logDrgDipService := service.NewLogDrgDipService(logDrgdipRepo)

	// 注册路由
	apiroutes.RegisterTaskRoutes(r, taskService)
	apiroutes.RegisterTaskLogRoutes(r, taskLogService)
	apiroutes.RegisterMappingRuleRoutes(r, mappingRuleService)
	apiroutes.RegisterSSHConfigRoutes(r, sshConfigService)
	apiroutes.RegisterDatasourceRoutes(r, dataSourceService)
	apiroutes.RegisterLogDrgDipRoutes(r, logDrgDipService)

	// 初始化logMed服务
	logMedRepo := repository.NewGormLogMedRepository(db)
	logMedService := service.NewLogMedService(logMedRepo)

	// 初始化hospital服务
	hospitalRepo := repository.NewGormHospitalRepository(db)
	hospitalService := service.NewHospitalService(hospitalRepo)

	// 初始化doctor服务
	doctorRepo := repository.NewGormHisDoctorRepository(db)
	doctorService := service.NewHisDoctorService(doctorRepo)

	// 初始化dept服务
	deptRepo := repository.NewGormHisDeptRepository(db)
	deptService := service.NewHisDeptService(deptRepo)

	// 初始化hospitalization服务
	hospRepo := repository.NewGormHospitalizationDetailRepository(db)
	hospService := service.NewHospitalizationDetailService(hospRepo)

	// 注册路由
	apiroutes.RegisterLogMedRoutes(r, logMedService)
	apiroutes.RegisterHospitalRoutes(r, hospitalService)
	apiroutes.RegisterDoctorRoutes(r, doctorService)
	apiroutes.RegisterDeptRoutes(r, deptService)
	apiroutes.RegisterHospitalizationRoutes(r, hospService)
}
